<template>
  <div>
    <!-- 警告文案 -->
    <el-alert
      title="注意：只允许为第三级分类设置相关参数！"
      type="warning"
    ></el-alert>
    <br />
    <!-- 联级选择器 -->
    <span class="demonstration">选择商品分类: </span>
    <el-cascader
      @change="getList()"
      v-model="selectedCateKeys"
      :options="Categories"
      :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }"
    ></el-cascader>
    <!-- 标签页 -->
    <el-tabs v-model="activeName" @tab-change="getList()">
      <el-tab-pane label="动态参数" name="many">
        <el-button
          type="primary"
          @click="
            model = {};
            dialogFormVisible = true;
          "
          >添加参数</el-button>
        <Table rowKey="attr_id" :column="col" :lists="manyTableData">
          <template v-slot:expands="{ row }">
            <el-tag
              :key="tag"
              v-for="(tag, index) in row.attr_vals"
              closable
              :disable-transitions="false"
              @close="handleClose(row, index)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.inputVisible"
              v-model="row.inputValue"
              ref="inputref"
              size="small"
              @keyup.enter="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >+ New Tag</el-button
            >
          </template>
          <template v-slot:action="{ row }">
            <el-button
              size="small"
              @click="
                model = { ...row };
                dialogFormVisible = true;
              "
              >编辑</el-button
            >
            <el-button size="small" type="danger">删除</el-button>
          </template>
        </Table>
      </el-tab-pane>

      <el-tab-pane label="静态属性" name="only">
        <el-button
          type="primary"
          @click="
            model = {};
            dialogFormVisible = true;
          "
          >添加属性</el-button
        >
        <Table rowKey="attr_id" :column="col" :lists="onlyTableData">
          <template v-slot:expands="{ row }">
            <el-tag
              :key="tag"
              v-for="(tag, index) in row.attr_vals"
              closable
              :disable-transitions="false"
              @close="handleClose(row, index)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.inputVisible"
              v-model="row.inputValue"
              ref="inputref"
              size="small"
              @keyup.enter="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >+ New Tag</el-button
            >
          </template>
          <template v-slot:action="{ row }">
            <el-button
              size="small"
              @click="
                model = { ...row };
                dialogFormVisible = true;
              "
              >编辑</el-button
            >
            <el-button size="small" type="danger">删除</el-button>
          </template>
        </Table>
      </el-tab-pane>
    </el-tabs>

    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="tit + title"
      :close-on-click-modal="false"
    >
      <el-form :model="model" label-width="120px" status-icon>
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="model.attr_name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="getAddParams()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, computed, ref } from "vue";
import api from "@/http/goods";
export default {
  name: "params",
  setup() {
    // const input = ref();
    const state = reactive({
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      //分类数据id
      selectedCateKeys: [],

      dialogFormVisible: false,

      list: [],

      model: {},

      col: [
        {
          type: "expand",
          width: "100px",
          align: "center",
          slot: "expands",
        },
        {
          label: "#",
          type: "index",
          width: "100px",
        },
        {
          label: "参数名称",
          prop: "attr_name",
        },
        {
          label: "操作",
          slot: "action",
          width: "400px",
          align: "center",
        },
      ],

      /**
       * 激活的名称
       */
      activeName: "many",
      /**
       * 分类列表
       */
      Categories: [],
    });
    /**
     * 渲染列表
     */
    let getList = async () => {
      console.log(199, state.selectedCateKeys);
      const res = await api.AttributeList(
        state.selectedCateKeys[2],
        state.activeName
      );
      console.log("参数列表", res);

      if (res.meta.status === 200) {
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          item.inputVisible = false;
          item.inputValue = "";
        });

        console.log(res.data);
        state.manyTableData = res.data;
        state.onlyTableData = res.data;
      }
    };
    /**
     * 点击按钮添加参数
     */
    let getAddParams = async () => {
      const res = await (state.model.attr_id
        ? api.UpdataAttribute
        : api.AddAttribute)(catId.value, {
        attr_id: state.model.attr_id,
        attr_name: state.model.attr_name,
        attr_sel: state.activeName,
      });
      console.log("carid", catId);
      if (res.meta.status == 200 || res.meta.status == 201) {
        state.dialogFormVisible = false;
        getList();
      }
    };

    /**
     * 获取分类数据
     */
    let getCategories = async () => {
      const res = await api.CategoriesList();
      console.log(res);
      if (res.meta.status == 200) {
        state.Categories = res.data;
      }
    };

    let saveAttrVals = async (row) => {
      let catId = state.selectedCateKeys[2];
      const res = await api.UpdataAttribute(
        catId,
        row.attr_id,
        row.attr_name,
        row.attr_sel,
        row.attr_vals.join(" ")
      );
      console.log("tag", res.data);
      if (res.meta.status === 200) {
        getList();
      }
    };

    let handleInputConfirm = async (row) => {
      let inputValue = row.inputValue;
      if (inputValue) {
        row.attr_vals.push(inputValue);
      }
      row.inputVisible = false;
      row.inputValue = "";
      //走接口
      let res = await api.UpdataAttribute(row.cat_id, {
        attr_id: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: state.activeName,
        attr_vals: row.attr_vals.join(" "),
      });
      if (res.meta.status === 200) {
        getList();
      }
    };

    // 点击按钮，展示文本输入框
    const inputref = ref();
    let showInput = (row) => {
      row.inputVisible = true;
      state.$nextTick(() => {
        console.log(22);
        inputref.focus();
      });
    };

    let handleClose = async (row, index) => {
      row.attr_vals.splice(index, 1);
      //走提交参数接口
      let res = await api.UpdataAttribute(row.cat_id, {
        attr_id: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: state.activeName,
        attr_vals: row.attr_vals.join(" "),
      });
      console.log("删除参数成功", res);
      if (res.meta.status === 200) {
        getList();
      }
    };

    onMounted(() => {
      getCategories();
    });

    let catId = computed(() => {
      if (state.selectedCateKeys.length === 3) {
        return state.selectedCateKeys[2];
      }
      return null;
    });

    let title = computed(() => {
      if (state.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    });

    let tit = computed(() => {
      return state.model.attr_id ? "编辑" : "添加";
    });

    return {
      ...toRefs(state), //导出数据
      // activeTab,
      title,
      tit,
      catId,
      showInput,
      inputref,
      // pid,
      saveAttrVals,
      getCategories, //获取分类数据
      getList,
      // getAddTags, //添加tag
      handleClose,
      handleInputConfirm,
      getAddParams,
      // getAddParams,

      // getupDateAttrValue,
      // show,
      // input,
      // delTag,
    };
  },
};
</script>

<style lang="scss" scoped>
.input {
  width: 100px;
}
</style>